module button(
	clk 			,
	rst_n			,
	key			,
	// key_r_flag  ,
	key_p_flag		// 检测按下标志	
	
);  


	input clk;
	input rst_n;
	input key;
	
	output reg key_p_flag;
	// output reg key_r_flag;
	
	reg sync_d0_key;
	reg sync_d1_key;
	reg pre_key;
	
	// parameter MCNT = 1_000_000 - 1;
	// Debug
	parameter MCNT = 10 - 1;
	
	reg [20:0] cnt;
	reg [1:0] state;  // 状态
	
	wire pedge_key;
	wire nedge_key;
	wire time_20ms_reached;
	
	localparam IDLE = 0;
	localparam P_STATE = 1;
	localparam W_STATE = 2;
	localparam R_STATE = 3;
	
	always@(posedge clk)
		sync_d0_key <= key;
	
	always@(posedge clk)
		sync_d1_key <= sync_d0_key;
	
	always@(posedge clk)
		pre_key 		<= sync_d1_key; 
	
	// 按键输入是上拉的
	assign nedge_key = (sync_d1_key == 0) && (pre_key == 1);
	assign pedge_key = (sync_d1_key == 1) && (pre_key == 0);
	
	
	
	// 20ms计数器，用来消抖
	always @(posedge clk or negedge rst_n)
		if (!rst_n)
			cnt <= 0;
		else if ((state == R_STATE) || (state == P_STATE))	
			begin 
				if (cnt <= MCNT) 
					cnt <= cnt + 1;
				else 
					cnt <= cnt;
			end 
		else 
			cnt <= 0;
	
	assign time_20ms_reached = (cnt >= MCNT);
	// 状态机
	always @(posedge clk or negedge rst_n)
		if (!rst_n)
			begin
				// key_r_flag <= 1'b0;
				key_p_flag <= 1'b0;
				state <= IDLE;
			end
		else begin 
			case (state)
			IDLE:	
				begin
					// key_r_flag <= 1'b0;
					if (nedge_key)
						state <= P_STATE;
				end
			P_STATE:	// 消抖状态
				begin
					if (time_20ms_reached)
						begin // 发送脉冲
							state <= W_STATE;
							key_p_flag <= 1'b1;
						end
					else if (pedge_key)
						state <= IDLE;
					else
						state <= P_STATE;
				end
			W_STATE:
				begin
					key_p_flag <= 1'b0;
					if (pedge_key)
						state <= R_STATE;
				end
			R_STATE: // 消抖状态
				begin
					if (time_20ms_reached)
						begin 
							state <= IDLE;
							// key_r_flag <= 1'b1; // 发送释放脉冲
						end
					else if (nedge_key)
						state <= W_STATE;
					else
						state <= R_STATE;
				end
			endcase
		end
endmodule
